<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
    <script src="./js/store.legacy.min.js"></script>
</head>

<body>
    <img width="100%" id="img1" src="./images/default.gif">
    <img width="100%" id="img2" src="./images/default.gif">
    <img width="100%" id="img3" src="./images/default.gif">
    <img width="100%" id="img4" src="./images/default.gif">
    <script type="text/javascript">
    /**
     * [oImg 基于localStroge的图片缓存]
     * @type {Image}
     */
    // var src = ['./images/7.png', './images/8.png', './images/9.png'];
    

    var src = ['./images/1.jpg','./images/7.png', './images/8.png', './images/9.png'];
    var isCache = false; //false表示本地没有缓存
    var indexC = 0;

    //获取缓存数据
    var oCaches = store.get('imgCache');
    var cacheArray = [];

    //检查是否已经缓存
    for (key in oCaches) {
        for (var k = 0; k < src.length; k++) {
            if (src[k] == key) {
                isCache = true;
                cacheArray.push(k);
            }
        }
    }

    //判断是否已经缓存
    if (!isCache) {

        for (var j = 0; j < src.length; j++) {
            //存储至本地的对象
            var o = {};
            loadImg(src[j], j + 1);
        }

    } else {

        for (var m = 0; m < cacheArray.length; m++) {
            cacheImg(m)
        }

    }

    //读取缓存图片
    function cacheImg(m) {
        var index = src[m];
        selectId('#img' + (m + 1)).setAttribute('src', oCaches[index]);
    }

    //读取服务器上的图片
    function loadImg(src, index) {

        var oImg = new Image();
        oImg.src = src;

        oImg.onload = function() {
            //展示图片
            selectId('#img' + index).setAttribute('src', src);
            //转码
            o[src] = getBase64Image(oImg);

            //将64位的编码保存至本地
            store.set('imgCache', o);
        };
    };

    //ID选择器
    function selectId(str) {
        return document.querySelector(str);
    }

    //转码
    function getBase64Image(img) {
        var canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, img.width, img.height);
        var dataURL = canvas.toDataURL("image/jpg");
        return dataURL
    }
    </script>
</body>

</html>
